<template>
  <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px">
    <el-tabs class="secondTabs" v-model="tabName" tab-position="top" style="margin-left: 8px">
      <el-tab-pane label="立项信息" name="projectbasicinfo">
        <div class="tl-form-line-title" style="margin-top:6px">
          基本信息
        </div>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="项目经理" prop="projectmanager">
              <el-input v-model="model.projectmanager" :disabled="true"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
              <el-input v-model="model.projectname" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo">
              <el-row type="flex">
                <el-select v-model="model.projectlevel" :disabled="true">
                  <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
                <el-button type="primary" icon="el-icon-edit-outline" class="levelButton" @click="openChangeLevelDialog" :disabled="true"></el-button>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectnumber">
              <el-input v-model="model.projectnumber" :disabled="true" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
              <el-date-picker :disabled="true" v-model="model.planstartdate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planStart"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
              <el-date-picker :disabled="true" v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd"> </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目周期" prop="bidcycle">
              <el-input :disabled="true" v-model="model.bidcycle" class="unitInput" placeholder="系统自动计算"><template #append>天</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="projectmanager">
              <el-input v-model="model.projectmanager" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="Sponsor" prop="sponsorcode" :rules="rules.rulesForInfo">
              <tl-ref-user :disabled="true" v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true"> </tl-ref-user>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Owner" prop="ownercode" :rules="rules.rulesForInfo" :disabled="true">
              <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true" :disabled="true"> </tl-ref-user>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row >
          <el-col :span="24" v-if="decisionusernameShow">
            <el-form-item label="决策组人员" prop="decisionusername" :rules="rules.rulesForInfo" >
              <el-input v-model="model.decisionusername" class="tl-ref-selector" :disabled="true">
                <el-button class="levelButton" slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog" :disabled="true"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row v-if="historyLevel && model.projectlevel !== historyLevel">
          <el-col :span="12">
            <el-form-item label="原项目级别">
              <el-input :disabled="true" v-model="historyLevel" class="tl-ref-selector"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="model.projectlevel && tempprojectlevel && model.projectlevel !== tempprojectlevel && !(model.purchasepattern === '1' && maxLevel === 3)">
          <el-col :span="24">
            <el-form-item label="项目级别调整原因" prop="changelevelreason" :rules="rules.rulesForInfo">
              <el-input :disabled="true" v-model="model.changelevelreason" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <a id="background" class="step-position">&nbsp;</a>
        <div class="tl-form-line-title">
          项目背景
        </div>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目背景概述" prop="background">
              <el-input :disabled="true" v-model="model.background" type="textarea" :rows="4" maxlength="1000" show-word-limit> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目目标" prop="target">
              <el-input :disabled="true" v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
       <!--        <el-row>-->
<!--          <el-col :span="24" v-if="model.invisibledemand === '1'">-->
<!--            <el-form-item label="客户需求分析" prop="clientdemand" :rules="rules.rulesForCustomeryInfo">-->
<!--              <el-input :disabled="true" v-model="model.clientdemand" type="textarea" :rows="6" maxlength="1000" show-word-limit> </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-collapse value="approval" :disabled="false">
          <el-collapse-item title="审批历史" name="approval">
            <template #title>
              <div class="tl-form-line-title">
                审批历史
              </div>
            </template>
            <div>
              <el-table v-show="listMode" class="tl-table" ref="mainTable" v-loading="loading" :data="datas" height="240px" @sort-change="doSortChange" row-key="id" border fit>
                <el-table-column type="index" label="序号" width="55px" align="center"> </el-table-column>
                <el-table-column prop="dispnodeid" label="流程节点" :show-overflow-tooltip="true" width="150px"> </el-table-column>
                <el-table-column prop="dispapprovaluserid" label="审批人" width="150px" align="center"> </el-table-column>
                <el-table-column prop="dispstate" label="状态" width="150px" align="center"> </el-table-column>
                <el-table-column prop="startdate" label="开始时间" width="160px" sortable="custom" sort-by="startdate" align="center"></el-table-column>
                <el-table-column prop="approvaldate" label="审批时间" width="160px" sortable="custom" sort-by="approvaldate" align="center"></el-table-column>
                <el-table-column prop="approvalcosttime" label="实际用时" width="160px" sortable="custom" sort-by="approvalcosttime" align="left"></el-table-column>
                <el-table-column prop="approvalopinion" label="审批意见" :show-overflow-tooltip="true" min-width="300px"> </el-table-column>
              </el-table>
              <!-- 列表分页 -->
              <el-row v-show="listMode" class="pagebar" ref="pager">
                <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-collapse value="approval" :disabled="false" v-if="changeapprovallist">
          <el-collapse-item title="项目信息变更审批历史" name="approval">
            <template #title>
              <div class="tl-form-line-title">
                项目信息变更审批历史
              </div>
            </template>
            <div>
              <el-table v-show="changeInfo.listMode" class="tl-table" ref="mainTable" v-loading="changeInfo.loading" :data="changeInfo.datas" height="240px" @sort-change="doSortChange" row-key="id" border fit>
                <el-table-column type="index" label="序号" width="55px" align="center"> </el-table-column>
                <el-table-column prop="dispnodeid" label="流程节点" :show-overflow-tooltip="true" width="150px"> </el-table-column>
                <el-table-column prop="dispapprovaluserid" label="审批人" width="150px" align="center"> </el-table-column>
                <el-table-column prop="dispstate" label="状态" width="150px" align="center"> </el-table-column>
                <el-table-column prop="startdate" label="开始时间" width="160px" sortable="custom" sort-by="startdate" align="center"></el-table-column>
                <el-table-column prop="approvaldate" label="审批时间" width="160px" sortable="custom" sort-by="approvaldate" align="center"></el-table-column>
                <el-table-column prop="approvalcosttime" label="实际用时" width="160px" sortable="custom" sort-by="approvalcosttime" align="left"></el-table-column>
                <el-table-column prop="approvalopinion" label="审批意见" :show-overflow-tooltip="true" min-width="300px"> </el-table-column>
              </el-table>
              <!-- 列表分页 -->
              <el-row v-show="changeInfo.listMode" class="pagebar" ref="pager">
                <el-pagination @size-change="doChangeSize2" @current-change="doChangeIndex2" :current-page="changeInfo.pageInfo.currentPage" :page-sizes="changeInfo.pageInfo.pageSizes" :total="changeInfo.pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <tl-attachment sourceType="GpmProject" :sourceId="model.id" :editable="false" style="position:absolute;right:480px;top:10px;"></tl-attachment>
    <el-button type="primary" style="position:absolute;right:380px;top:10px;" @click.native="openProjectChange()">立项变更</el-button>
    <el-button type="primary" style="position:absolute;right:280px;top:10px;" @click.native="openProjectChangeHistory()">变更历史</el-button>
    <el-button type="primary" style="position:absolute;right:140px;top:10px;" @click.native="$refs.history.visible=true">立项审批历史</el-button>
    <el-button type="primary" style="position:absolute;right:10px;top:10px;" @click.native="$refs.changeHistory.visible=true" :disabled="disableChangeHistory">变更审批历史</el-button>
    <tl-sd-project-change ref="projectChanger"></tl-sd-project-change>
    <history-table ref="historyTableRef" :tabled-list="'/sd/projectHistory/list'" :parentValue="model.id + ''" :parentField="'projectid'" :top-source-type="'GpmProjectHistory'"></history-table>
    <approval-history ref="history" :history-myflow-id="'history-myflow-1'" sourceType="GpmWfForm" :sourceId="model.approvalhistoryid ? model.approvalhistoryid : 0"></approval-history>
    <approval-history ref="changeHistory" :history-myflow-id="'history-myflow-2'" sourceType="GpmWfForm" :sourceId="model.approvalchangeid ? model.approvalchangeid : 0"></approval-history>
  </el-form>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
import { mixin_edit } from '@tapui/mixins/mixin_edit'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlChangeLevelRef from './changeLevelCompent'
import tlSdProjectChange from '@/views/gpm/gpmProjectHistory/edit'
import historyTable from './historyListChangeLog/table'
import approvalHistory from "@/views/gpm/gpmProject/component/approvalHistory"
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_list, mixin_edit],
  components: { tlChangeLevelRef, tlSdProjectChange, historyTable, approvalHistory },
  data() {
    return {
      bidrequired: true,
      moduleTitle: '项目立项',
      urlPrefix: '/sd/project/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/sd/project/queryOrgByDeptId',
        nodeInsList: '/cbo/approvalNodeIns/list',
        wfFormList: '/sd/wfForm/list',
        checkCirculatedRecord: '/sd/project/checkCirculatedRecord',
        queryCirculatedIdByProjectCode: '/sd/projectCirculated/queryCirculatedIdByProjectCode',
        approvalList: '/sd/project/approvalList',
        ifReviewed: '/sd/projectReview/ifReviewed'
      },
      sorterInfo: {
        // 排序参数
        sidx: 'createon',
        sord: 'desc'
      },
      midChangePoint: true,
      datas: [],
      changedatas: [],
      changeapprovallist: false,
      circulateapprovallist: false,
      approvalcosttime: '',
      days: '',
      shengyvhour: '',
      hours: '',
      shengyvminute: '',
      minutes: '',
      projectcode: '',
      disableChangeHistory: false,
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      changeInfo: {
        loading: false,
        datas: [],
        approvalcosttime: '',
        days: '',
        shengyvhour: '',
        hours: '',
        shengyvminute: '',
        minutes: '',
        listMode: true,
        circulatedId: 0,
        pageInfo: {
          // 分页参数
          currentPage: 1, // 当前页面
          pageSize: 10, // 每页记录数
          pageSizes: ['10', '50', '100'],
          totalCount: 0 // 总数
        }
      },
      circulateInfo: {
        loading: false,
        datas: [],
        approvalcosttime: '',
        days: '',
        shengyvhour: '',
        hours: '',
        shengyvminute: '',
        minutes: '',
        listMode: true,
        circulatedId: 0,
        pageInfo: {
          // 分页参数
          currentPage: 1, // 当前页面
          pageSize: 10, // 每页记录数
          pageSizes: ['10', '50', '100'],
          totalCount: 0 // 总数
        }
      },
      loading: false,
      visible: false,
      listMode: true,
      tabName: 'projectbasicinfo',
      // 项目级别默认编码值，根据选择的机会点确定
      tempprojectlevel: '',
      // 项目级别默认显示值，根据选择的机会点确定
      tempdispprojectlevel: '',
      // 项目等级，例：网级、省级等
      maxLevel: -1
    }
  },
  props: {
    projectId: Number,
    projectinfo: {},
    // 来自于哪个index组件
    fromIndexType: {
      type: String,
      default: ''
    }
  },
  computed: {
    historyLevel() {
      if (this.model.levelhistory) {
        return JSON.parse(this.model.levelhistory.replace(/\//g, '')).oldprojectlevel
      } else {
        return ''
      }
    },
    showAddContactInfo() {
      if (!this.model.contractcode && (this.model.sourcetype === '2' || this.model.sourcetype === '3')) {
        return true
      } else {
        return false
      }
    },
    ifOutContractable() {
      if (this.model.outcontractable === '1') {
        return true
      } else {
        return false
      }
    },
    // 决策组成员控制
    decisionusernameShow() {
      if (this.model.decisionusername !== '' && this.model.decisionusername !== undefined && this.model.decisionusername !== null) {
         return true
      } else {
         return false
      }
    }
  },
  methods: {
    refreshAttachment() {
      this.$refs.contractAttachmentRef.loadData()
    },
    openAddContractInfo() {
      this.$refs.addContractInfoRef.open()
    },
    openProjectChangeHistory() {
      this.$refs.historyTableRef.open()
    },
    changepurchasepattern(value) {
      if (value === '8') {
        this.bidrequired = false
      } else {
        this.bidrequired = true
      }
    },
    planStart(e) {
      var a = new Date(this.model.planstartdate)
      var b = new Date()
    },
    planEnd(e) {
      if (this.model.planstartdate === '' || typeof this.model.planstartdate === 'undefined') {
        this.$tap.alert('请先选择计划开始日期！', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var c = new Date(this.model.planenddate).getTime()
      var d = new Date(this.model.planstartdate).getTime()
      if (c < d) {
        this.$tap.alert('开始日期不得大于结束日期。', 'warning')
        this.$set(this.model, 'planenddate', '')
        this.$set(this.model, 'bidcycle', '')
        return
      }
      var a = c - d
      var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
      this.$set(this.model, 'bidcycle', days)
    },
    openProjectChange() {
      var param = {
        qry_projectcode: this.projectinfo.projectcode
      }
      if ((this.model.projectmanagercode !== this.$store.getters.user.code && this.$store.getters.user.adminlevel !== 9) || this.fromIndexType === 'file') {
        param.qry_state = "1"
      } else {
        param.qry_state = "0,1,2"
      }
      getAction('/sd/projectHistory/list', param).then((res) => {
        // 如果当前用户是项目经理才可编辑，如果来自于归档模块则能查看
        if ((this.model.projectmanagercode !== this.$store.getters.user.code && this.$store.getters.user.adminlevel !== 9) || this.fromIndexType === 'file') {
          if (res.result.dataList.length !== 0) {
            this.openViewDialog('projectChanger', res.result.dataList[0].id)
          } else {
            this.$tap.alert('该项目暂时没有变更记录', 'warning')
          }
        } else {
          if (res.result.dataList.length === 0) {
            this.openAddDialog('projectChanger', this.model)
          } else {
            this.openEditDialog('projectChanger', res.result.dataList[0].id)
          }
        }
      })
    },
    /** 打开新增对话框实现 */
    openAddDialog(editForm, rowData) {
      getAction(this.url.ifReviewed, { projectid: this.projectinfo.id }).then((res) => {
        if (res.success) {
          if (res.result) {
            this.$tap.alert('该项目已提交复盘审批，无法新增单据!')
          } else {
            if (!this.beforeOpenAddDialog(editForm, rowData)) {
              return
            }
            let copymodel = {}
            Object.assign(copymodel, rowData)
            this.$refs[editForm].projectmodel = rowData
            this.$refs[editForm].isAdd = true
            this.$refs[editForm].visible = true
            this.$refs[editForm].disableEditSubmit = false
            this.$nextTick(() => {
              this.afterOpenAddDialog(editForm, rowData)
            })
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
      .catch((err) => {
        this.$tap.alert(err, 'warninig')
      })
    },
    /** 加载审批历史列表数据 */
    loadData(paramMap) {
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      // var params = this.getQueryParams()
      let params = {
        currentPage: this.pageInfo.currentPage,
        pageSize: this.pageInfo.pageSize,
        qry_wfsourceid: this.projectId,
        qry_sourcetype: 'GpmWfForm',
        sidx: 'approvaldate',
        sord: 'desc'
      }
      // 清除垃圾数据
      this.approvalcosttime = ''
      this.days = ''
      this.shengyvhour = ''
      this.hours = ''
      this.shengyvminute = ''
      this.minutes = ''
      // 数据查询
      this.loading = true
      getAction(this.url.approvalList, params)
        .then((res) => {
          if (res.success) {
            // 增加展示审批用时
            this.addCostTime(res)
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    queryChangeHistory() {
      let wfParam = {
        qry_finalsourceid: this.projectinfo.id,
        qry_finalsourcetype: "gpmProject",
        qry_sourcetype: "GpmProjectHistory",
        qry_businesstype: "20",
        qry_state: '1,2,9',
        sidx: 'createon',
        sord: 'desc',
        pageSize: 10,
        currentPage: 1
      }
      // 清除垃圾数据
      this.changeInfo.approvalcosttime = ''
      this.changeInfo.days = ''
      this.changeInfo.shengyvhour = ''
      this.changeInfo.hours = ''
      this.changeInfo.shengyvminute = ''
      this.changeInfo.minutes = ''
      // 数据查询
      this.changeInfo.loading = true
      getAction(this.url.wfFormList, wfParam).then((res) => {
        if (res.success) {
          if (res.result.dataList.length > 0) {
            this.changeapprovallist = true
            // 查询变更审批历史
            let changeparams = {
              currentPage: this.changeInfo.pageInfo.currentPage,
              pageSize: this.changeInfo.pageInfo.pageSize,
              qry_sourceid: res.result.dataList[0].id,
              qry_sourcetype: 'GpmWfForm',
              sidx: 'approvaldate',
              sord: 'desc'
            }
            getAction(this.url.nodeInsList, changeparams).then((t) => {
              if (t.success) {
                this.addCostTime(t)
                this.changeInfo.datas = t.result.dataList
                this.changeInfo.pageInfo.totalCount = t.result.totalCount
              }
              this.changeInfo.loading = false
            }).catch((e) => {
              this.changeInfo.loading = false
            })
          } else {
            this.changeapprovallist = false
          }
        }
      })
    },
    addCostTime(res) {
      for (let i = 0; i < res.result.dataList.length; i++) {
        if (res.result.dataList[i].approvaldate !== null && res.result.dataList[i].startdate !== null) {
          let a = new Date(res.result.dataList[i].approvaldate).getTime() - new Date(res.result.dataList[i].startdate).getTime()
          // 1天的毫秒数
          let daymiseconds = 1000 * 60 * 60 * 24
          // 1小时的毫秒数
          let hourmiseconds = 60 * 60 * 1000
          // 1分钟的毫秒数
          let minutesmiseconds = 60 * 1000
          if (a > daymiseconds) {
            this.days = Math.floor(a / daymiseconds)
            this.shengyvhour = a - this.days * daymiseconds
            this.hours = Math.floor(this.shengyvhour / hourmiseconds)
            this.shengyvminute = this.shengyvhour - this.hours * hourmiseconds
            this.minutes = Math.floor(this.shengyvminute / minutesmiseconds)
            this.approvalcosttime = this.days + '天' + this.hours + '小时' + this.minutes + '分钟'
            this.$set(res.result.dataList[i], 'approvalcosttime', this.approvalcosttime)
          } else if (a > hourmiseconds) {
            this.hours = Math.floor(a / hourmiseconds)
            this.shengyvminute = a - this.hours * hourmiseconds
            this.minutes = Math.floor(this.shengyvminute / minutesmiseconds)
            this.approvalcosttime = '0天' + this.hours + '小时' + this.minutes + '分钟'
            this.$set(res.result.dataList[i], 'approvalcosttime', this.approvalcosttime)
          } else {
            this.minutes = Math.floor(a / minutesmiseconds)
            this.approvalcosttime = '0天0小时' + this.minutes + '分钟'
            this.$set(res.result.dataList[i], 'approvalcosttime', this.approvalcosttime)
          }
        }
      }
    },
    /** 查询传阅反馈审批历史 **/
    queryCirculateHistory() {
      // 先查询sourceid
      getAction(this.url.queryCirculatedIdByProjectCode, { projectcode: this.projectinfo.projectcode }).then((res) => {
        if (res.success) {
          // 若没有传阅反馈审批历史则直接返回
          if (!res.result.id) {
            this.circulateapprovallist = false
            return
          }
          let params = {
            currentPage: this.circulateInfo.pageInfo.currentPage,
            pageSize: this.circulateInfo.pageInfo.pageSize,
            qry_sourceid: res.result.id,
            sidx: 'approvaldate',
            sord: 'desc'
          }
          // 清除垃圾数据
          this.circulateInfo.approvalcosttime = ''
          this.circulateInfo.days = ''
          this.circulateInfo.shengyvhour = ''
          this.circulateInfo.hours = ''
          this.circulateInfo.shengyvminute = ''
          this.circulateInfo.minutes = ''
          // 数据查询
          this.circulateInfo.loading = true
          getAction(this.url.nodeInsList, params)
            .then((res) => {
              if (res.success) {
                this.circulateapprovallist = res.result.dataList.length > 0
                // 增加展示审批用时
                this.addCostTime(res)
                this.circulateInfo.datas = res.result.dataList
                this.circulateInfo.pageInfo.totalCount = res.result.totalCount
              } else {
                this.$tap.alert(res.message, 'warning')
              }
              this.circulateInfo.loading = false
            })
            .catch((err) => {
              this.circulateInfo.loading = false
            })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(() => {
        // this.getFieldsCustomSetting('projectpolymerization', 'el-form')
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '添加' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
      })
      this.datas = []
      // this.loadData({ currentPage: 1 })
    },
    /** 执行查询 */
    // doQuery() {
    //   this.loadData({ currentPage: 1 })
    // },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {
        qry_sourcetype: 'gpmProject',
        qry_sourceid: 0
      }
      if (!this.isAdd) {
        param.qry_sourceid = this.projectId
      }
      Object.assign(param, this.sorterInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return param
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace('ending', '')
      // this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    /** 每页大小改变 */
    doChangeSize2(val) {
      if (this.changeInfo.pageInfo.pageSize !== val) {
        this.changeInfo.pageInfo.pageSize = val
        this.changeInfo.pageInfo.currentPage = 1
        this.queryChangeHistory()
      }
    },
    /** 页面跳转 */
    doChangeIndex2(val) {
      if (this.changeInfo.pageInfo.currentPage !== val) {
        this.changeInfo.pageInfo.currentPage = val
        this.queryChangeHistory()
      }
    },
    /** 每页大小改变 */
    doChangeSize3(val) {
      if (this.circulateInfo.pageInfo.pageSize !== val) {
        this.circulateInfo.pageInfo.pageSize = val
        this.circulateInfo.pageInfo.currentPage = 1
        // this.queryCirculateHistory()
      }
    },
    /** 页面跳转 */
    doChangeIndex3(val) {
      if (this.circulateInfo.pageInfo.currentPage !== val) {
        this.circulateInfo.pageInfo.currentPage = val
        // this.queryCirculateHistory()
      }
    },
    /** 打开传阅反馈编辑页 **/
    openCirculateDialog() {
      // 判断当前项目是否有传阅反馈记录
      if (this.model.projectcode) {
        getAction(this.url.checkCirculatedRecord, { code: this.model.projectcode })
          .then((res) => {
            if (res.success) {
              // 如果当前用户是项目经理才可编辑，如果来自于归档模块则之恶能查看
              if ((this.model.projectmanagercode !== this.$store.getters.user.code && this.$store.getters.user.adminlevel !== 9)) {
                if (res.result.hasrecord) {
                  this.openViewDialog('projectCirculated', res.result.circulatedrecord.id)
                } else {
                  this.$tap.alert('该项目暂时没有传阅反馈记录', 'warning')
                }
              } else {
                if (res.result.hasrecord) {
                  this.openEditDialog('projectCirculated', res.result.circulatedrecord.id)
                } else {
                  this.openAddDialog('projectCirculated', this.model)
                }
              }
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
          .catch((err) => { })
      }
    },
    beforeOpenAddDialog(editForm, rowData) {
      this.$refs[editForm].projectModel = rowData
      return true
    },
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      return getAction(this.url.load, { id: id }).then((res) => {
        if (res.success) {
          this.model = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 数据库字符串对象去特殊字符
    loaded() {
      if (this.model.productrange && !Array.isArray(this.model.productrange)) {
        var arrStr = this.model.productrange
        arrStr.replace(/\//g, '')
        this.model.productrange = JSON.parse(arrStr)
      }
      // 通过项目级别编码为项目级别显示值赋值
      if (this.model.projectlevel && !this.model.projectdefaultlevel && this.codeModel.projectlevelList) {
        let tempLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel)
        // 若项目默认级别为空则为tempprojectlevel和tempdispprojectlevel赋值
        this.tempprojectlevel = this.model.projectlevel
        this.tempdispprojectlevel = tempLevelData.name
      }
      // 通过项目默认等级为tempprojectlevel和tempdispprojectlevel赋值
      if ((this.model.projectdefaultlevel || this.model.projectdefaultlevel === '0') && this.codeModel) {
        let tempDefaulLevelData = this.codeModel.projectlevelList.find((item) => item.code === this.model.projectdefaultlevel)
        this.tempprojectlevel = this.model.projectdefaultlevel
        this.tempdispprojectlevel = tempDefaulLevelData.name
      }
      // 给midChangePoint赋初始值
      if (this.model.chanceclue) {
        this.midChangePoint = this.model.chanceclue.split(',') <= 1
      }
    },
    /** 修改项目来源时将机会点/线索编号、项目名称、项目金额、默认等级、级别调整原因和其他中间变量清空 **/
    changeSource(select) {
      this.$set(this.model, 'chanceclue', '')
      this.$set(this.model, 'projectname', '')
      this.$set(this.model, 'ourprocductfund', '')
      this.$set(this.model, 'projectdefaultlevel', '')
      this.$set(this.model, 'changelevelreason', '')
      this.$set(this.model, 'projectlevel', '')
      this.$set(this.model, 'productrange', [])
      this.tempprojectlevel = ''
      this.tempdispprojectlevel = ''
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      if (!this.model.projectsource) {
        this.$tap.alert('请先选择项目来源！', 'warning')
      } else {
        this.$refs.changeRef.visible = true
      }
    },
    /** 打开调整项目级别的弹框 **/
    openChangeLevelDialog() {
      this.$refs.changeLevelRef.projectlevelList = this.codeModel.projectlevelList
      this.$refs.changeLevelRef.dispprojectdefaultlevel = this.tempdispprojectlevel
      this.$set(this.$refs.changeLevelRef.model, 'projectlevel', this.model.projectlevel)
      this.$set(this.$refs.changeLevelRef.model, 'dispprojectlevel', this.codeModel.projectlevelList.find((item) => item.code === this.model.projectlevel).name)
      this.$set(this.$refs.changeLevelRef.model, 'changelevelreason', this.model.changelevelreason)
      this.$refs.changeLevelRef.visible = true
    }
  },
  mounted() {
    this.queryData(this.projectId).then((_) => {
      // 获取项目等级
      this.loaded()
    })
    this.loadData({ currentPage: 1 })
    this.queryChangeHistory()
    // this.queryCirculateHistory()
    // this.queryApprovalHistory()
    // this.loadData({})
  }
}
</script>
<style scoped>
.formLine {
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 12%;
  font-family: "kaiTi";
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
<style lang="scss" scoped>
/deep/ .el-collapse-item__header {
  font-size: 18px !important;
  font-weight: bold;
}
/deep/ .el-tabs--border-card {
  box-shadow: 0 0;
  -webkit-box-shadow: 0 0;
}
.secondTabs {
  padding-top: 5px;
  padding-bottom: 6px;
  /deep/ .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }
  /deep/ .el-tabs__nav-wrap::after {
    display: none;
  }
  /deep/ .el-tabs__active-bar {
    height: 1px;
  }
}
/** 表格样式相关 */
.tl-table {
  /** “暂无数据”居中显示 */
  /deep/ .el-table__empty-block {
    justify-content: center;
    align-items: center;
    padding: 0;
  }
  /deep/ .el-table__empty-text {
    text-align: center;
  }
  // 控制边框
  /deep/ .gutter {
    display: none !important;
  }
}
</style>
